package com.wonders.hs.pd.mm.web.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.wonders.hs.pd.mm.web.bean.MessageInfo;
import com.wonders.hs.pd.mm.web.bean.ResponseResult;
import com.wonders.hs.pd.mm.web.bean.UserDeptRelation;
import com.wonders.hs.pd.mm.web.bean.UserModel;
import com.wonders.hs.pd.mm.web.config.SystemConfig;
import com.wonders.hs.pd.mm.web.message.MessageHandler;
import com.wonders.hs.pd.mm.web.utils.HttpRequestUtils;
import com.wonders.hs.pd.mm.web.utils.JDBCConnect;
import com.wonders.hs.pd.mm.web.utils.JsonUtil;

import net.minidev.json.JSONObject;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author banglong
 * @date 2016/8/18.
 */
@RestController
@RequestMapping("/api")
public class ApiController {

	// 系统异常
	private final static Logger logger = LoggerFactory.getLogger(ApiController.class);
	private static final String SYSTEM_ERROR_INFO = "\"{'issuccess':1,'message':'系统异常，请联系管理员'}\"";
	private static final String SESSION_IS_EXPIRED = "\"{'isSessionInvalidated':true}\"";

	/**
	 * 大部分接口的统一访问地址，该方法只能访问参数数组的第一个 需要 session 验证 当session中保存的 用户ID 为空的时候 发送信息
	 * 让前端做登陆页跳转
	 *
	 * @param params
	 *            参数
	 * @param request
	 *            request
	 * @param session
	 *            session
	 */
	@RequestMapping(value = "/sendPostRequest", method = RequestMethod.POST)
	public String fetchDataByClassNameAndMethod(@RequestBody Map<String, Object> params, HttpServletRequest request,
			HttpSession session) {
		String url = SystemConfig.API_ADDRESS + params.get("className").toString() + "/"
				+ params.get("method").toString(); // 访问地址

		// 访问前做 session 验证 验证成功才可以继续操作
		String checkResult = checkingSession(session);
		if (!StringUtils.isEmpty(checkResult))
			return checkResult;

		String result = HttpRequestUtils.sendPost(url, params);
		// 如果不是 json 串 提示 失败
		if (result.contains("<html>") || result.contains("Exception")) {
			UserModel userInfo = (UserModel) session.getAttribute("currentUser");
			String log = "员工id：" + userInfo.getYgid() + "，员工姓名：" + userInfo.getXm() + "，Exception：" + result;
			logger.error("/" + params.get("className") + "/" + params.get("method").toString() + "  " + log, result);
			//result = SYSTEM_ERROR_INFO;
		}
		return result;
	}
	
	/**
	 * 阳光申请 维护 
	 * @param params
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/sunMaint", method = RequestMethod.POST)
	public String sunMaint(@RequestBody Map<String, Object> params, HttpServletRequest request,
			HttpSession session) {
		String url = SystemConfig.API_ADDRESS + params.get("className").toString() + "/"
				+ params.get("method").toString(); // 访问地址
		// 访问前做 session 验证 验证成功才可以继续操作
		String checkResult = checkingSession(session);
		if (!StringUtils.isEmpty(checkResult))
			return checkResult;
	    String condition = (String) params.get("condition"); 
		String result = HttpRequestUtils.sendPost(url, params);
		// 如果不是 json 串 提示 失败
		if (result.contains("<html>") || result.contains("Exception")) {
			UserModel userInfo = (UserModel) session.getAttribute("currentUser");
			String log = "员工id：" + userInfo.getYgid() + "，员工姓名：" + userInfo.getXm() + "，Exception：" + result;
			logger.error("/" + params.get("className") + "/" + params.get("method").toString() + "  " + log, result);
			result = SYSTEM_ERROR_INFO;
		}
		return result;
	}
	
	
	

	/**
	 * 获取所有科室信息 无需session验证
	 */
	@RequestMapping(value = "/getDepartments", method = RequestMethod.POST)
	public String getDepartments(@RequestBody Map<String, Object> params, HttpSession session) {
		String url = SystemConfig.API_ADDRESS + "OrganizationManager" + "/GetOutDTODepts"; // 访问地址
		String result = HttpRequestUtils.sendPost(url, params);
		// 如果不是 json 串 提示 失败
		if (result.contains("<html>")) {
			result = SYSTEM_ERROR_INFO;
		}
		return result;
	}
	/**
	 * 获取用户所有角色 无需session验证
	 */
	@RequestMapping(value = "/GetRolesOfUser", method = RequestMethod.POST)
	public String GetRolesOfUser(@RequestBody Map<String, Object> params, HttpSession session) {
		String url = SystemConfig.API_ADDRESS + "AuthorizationManager" + "/GetRolesOfUser"; // 访问地址
		String result = HttpRequestUtils.sendPost(url, params);
		// 如果不是 json 串 提示 失败
		if (result.contains("<html>")) {
			result = SYSTEM_ERROR_INFO;
		}
		return result;
	}

	/**
	 * 登录验证 无需session验证
	 */
	@RequestMapping(value = "/loginAuthentication", method = RequestMethod.POST)
	public String loginAuthentication(@RequestBody Map<String, Object> params, HttpSession session) {
		String url = SystemConfig.API_ADDRESS + "AuthenticationManager" + "/NPLogin"; // 访问地址
		String result = HttpRequestUtils.sendPost(url, params);
		// 如果不是 json 串 提示 失败
		if (result.contains("<html>")) {
			result = SYSTEM_ERROR_INFO;
		}
		return result;
	}

	/**
	 * 获取用户信息 无需session验证
	 */
	@RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
	public ResponseResult getUserInfo(@RequestBody Map<String, Object> params, HttpSession session) {
		String url = SystemConfig.API_ADDRESS + "AuthenticationManager" + "/GetUser"; // 访问地址
		String result = HttpRequestUtils.sendPost(url, params); // 发送登录请求
		ObjectMapper objectMapper = new ObjectMapper();
		ResponseResult responseResult = null;
		Map<String, String> userInfo;
		// session 中保存用户信息
		try {
			responseResult = objectMapper.readValue(result, ResponseResult.class);
			if (!"null".equals(responseResult.getResult())) {
				userInfo = objectMapper.readValue(responseResult.getResult(), Map.class);
				userInfo.put("Pass", "");
				UserModel userModel = buildUserModel(userInfo);
				session.setAttribute("currentUser", userModel);
				responseResult.setResult(objectMapper.writeValueAsString(userInfo));
			}
		} catch (IOException e) {
			logger.error("/getUserInfo", e);
		}
		return responseResult;
	}

	/**
	 * 更新登录信息
	 */
	@RequestMapping("/updateUserLoginInfo")
	public String updateUserLoginInfo(@RequestBody Map<String, Object> params) {
		// 更新登录信息
		String url = SystemConfig.API_ADDRESS + "UserLoginInfoManager" + "/updateUserLoginInfo"; // 访问地址
		String result = HttpRequestUtils.sendPost(url, params);
		// 如果不是 json 串 提示 失败
		if (result.contains("<html>")) {
			result = SYSTEM_ERROR_INFO;
		}
		return result;
	}

	/**
	 * 获取科室信息 无需session验证
	 */
	@RequestMapping(value = "/getDepartmentsByUser", method = RequestMethod.POST)
	public String getDepartmentsByUser(@RequestBody Map<String, Object> params, HttpSession session) {
		String url = SystemConfig.API_ADDRESS + "OrganizationManager" + "/GetDeptOfUser"; // 访问地址
		String result = HttpRequestUtils.sendPost(url, params);
		// 如果不是 json 串 提示 失败
		if (result.contains("<html>")) {
			result = SYSTEM_ERROR_INFO;
		}
		return result;
	}

	/**
	 * 获取菜单信息
	 */
	@RequestMapping(value = "/getSystemMenu", method = RequestMethod.POST)
	public String getSystemMenu(HttpSession session) {

		// 访问前做 session 验证 验证成功才可以继续操作
		String checkResult = checkingSession(session);
		if (!StringUtils.isEmpty(checkResult))
			return checkResult;
		return (String) session.getAttribute("menu");
	}

	/**
	 * 获取账户信息
	 */
	@RequestMapping(value = "/balanceQuery", method = RequestMethod.POST)
	public String balanceQuery(@RequestBody Map<String, Object> params) {
		// List<Map<String, String>> list = null;
		// // 科室id
		// String deptAccountID = params.get("deptAccountID");
		// // 开始时间
		// String startTime = params.get("startTime");
		// // 结束时间
		// String endTime = params.get("endTiem");
		// if (!StringUtils.isEmpty(deptAccountID) &&
		// !StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
		// list = JDBCConnect.balanceQuery(deptAccountID, startTime, endTime);
		// }
		String url = SystemConfig.API_ADDRESS + "MoveBillQueryManager" + "/GetAccountBalanceReport"; // 访问地址
		String result = HttpRequestUtils.sendPost(url, params);
		// 如果不是 json 串 提示 失败
		if (result.contains("<html>")) {
			result = SYSTEM_ERROR_INFO;
		}
		return result;
	}

	/**
	 * SSO 登录 无需session验证
	 */
	@RequestMapping(value = "/ssoLogin", method = RequestMethod.POST)
	public String SSOLogin(@RequestBody Map<String, Object> params) {
		String url = SystemConfig.SSO_LOGIN_URL + "SsoLogin"; // 访问地址
		return HttpRequestUtils.sendPost(url, params);
	}

	/**
	 * SSO 修改密码 无需session验证
	 */
	@RequestMapping(value = "/ssoChangePassword", method = RequestMethod.POST)
	public String SSOChangePassword(@RequestBody Map<String, Object> params) {
		// todo change password
		String url = SystemConfig.SSO_LOGIN_URL + "passWordManager/setPassWord"; // 访问地址
		return HttpRequestUtils.sendPost(url, params);
	}

	/**
	 * 领用收货单查询 无需session验证
	 */
	@RequestMapping(value = "/billQuery", method = RequestMethod.POST)
	public List billQuery(String id) {
		return JDBCConnect.billQuery(id);
	}

	/**
	 * 测试
	 */
	@RequestMapping("/getGoodsToDataSet")
	public String getGoodsToDataSet(@RequestBody Map<String, Object> params, HttpSession session) {
          Map map=new HashMap<>();
          map.entrySet();
		// 访问前做 session 验证 验证成功才可以继续操作
		String checkResult = checkingSession(session);
		if (!StringUtils.isEmpty(checkResult))
			return checkResult;

		String url = SystemConfig.API_ADDRESS + "GoodsManager/SelectGoodsToDept";

		return "";
	}

	// 获取 维护公告信息
	@RequestMapping(value = "/getMessageInfo", method = RequestMethod.POST)
	public MessageInfo getMessageInfo() {
		if (MessageHandler.currentMsg != null) {
			return MessageHandler.currentMsg;
		} else {
			return new MessageInfo();
		}
	}

	/**
	 * 测试 session
	 */
	public static String checkingSession(HttpSession session) {
		String result = null;
		if (session == null || session.getAttribute("currentUser") == null) {
			HashMap<String, Object> map = new HashMap<>();
			map.put("isSessionInvalidated", true);
			try {
				result = new ObjectMapper().writeValueAsString(map);
			} catch (JsonProcessingException e) {
				logger.error("checkingSession", e);
			}
		}
		return result;
	}

	private UserModel buildUserModel(Map<String, String> map) {
		UserModel userModel = new UserModel();
		userModel.setLx(map.get("Lx") != null ? map.get("Lx").trim() : "");
		userModel.setMs(map.get("Ms") != null ? map.get("Ms").trim() : "");
		userModel.setXgbz(map.get("Xgbz") != null ? map.get("Xgbz").trim() : "");
		userModel.setXm(map.get("Xm") != null ? map.get("Xm").trim() : "");
		userModel.setYggh(map.get("Yggh") != null ? map.get("Yggh").trim() : "");
		userModel.setYgid(map.get("Ygid") != null ? map.get("Ygid").trim() : "");
		userModel.setPass(map.get("Pass") != null ? map.get("Pass").trim() : "");
		return userModel;
	}

	@RequestMapping(value = "/ResetUserDept", method = RequestMethod.POST)
	  public String ResetUserDept(@RequestBody Map<String, Object> params) {
	    // 更新登录信息
	    String url = SystemConfig.API_ADDRESS + "OrganizationManager" + "/ResetUserDept"; // 访问地址
	    String result = HttpRequestUtils.sendPost(url, params);
	    // 如果不是 json 串 提示 失败
	    if (result.contains("<html>")) {
	      result = SYSTEM_ERROR_INFO;
	    }
	    return result;
	  }
	
	@RequestMapping(value = "/isDept", method = RequestMethod.POST)
	  public String isDept(@RequestBody Map<String, Object> params) throws JsonParseException, JsonMappingException, IOException {
	    // 更新登录信息
	    String url = SystemConfig.API_ADDRESS + "OrganizationManager" + "/GetDepts"; // 访问地址
	    String result = HttpRequestUtils.sendPost(url, params);
	    Map resultMap = JsonUtil.json2Bean1(result, Map.class);
	    
	    String value = (String) resultMap.get("result"); 
	    
	    String josn=value.substring(1, value.length()-1);
	   Map resultMapalue1 = JsonUtil.json2Bean1(josn, Map.class);
	   String yxbz = (String) resultMapalue1.get("yxbz"); 
	    return yxbz;
	  }


}
